package tau.dimes.tasks;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

import tau.dimes.data.Table;
import tau.dimes.data.TableException;
import tau.dimes.db.Database;
import tau.dimes.db.DatabaseException;
import tau.dimes.db.DatabaseFactory;

public class LoadTableTask extends FutureTask<Table>
{
	public LoadTableTask(final String server, final String query, final int startRow, final int rowCount)
	{
		super(new Callable<Table>() {
			@Override
			public Table call() throws Exception
			{
				return loadTable(server, query, startRow, rowCount);
			}
		});
	}

	private static Table loadTable(String server, String query, int startRow, int rowCount) throws DatabaseException,
		SQLException, TableException
	{
		String limitedQuery = query.trim() + " LIMIT " + startRow + "," + rowCount;
		Database db = DatabaseFactory.create(server);
		ResultSet rs = db.executeQuery(limitedQuery);
		Table table = new Table(rs);
		rs.close();
		return table;
	}
}
